package org.monkeyk.io;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.UUID;

/**
 * @author Zhang Hui
 * @author Shengzhao Li
 */
public class DefaultFileWarehouse implements FileWarehouse {

    public static final String DEFAULT_UPLOAD_PATH = "../upload/";
    private static Logger log = LoggerFactory.getLogger(DefaultFileWarehouse.class);

    //Upload file directory
    private String uploadPath = DEFAULT_UPLOAD_PATH;


    public DefaultFileWarehouse() {
        initialUploadDir();
    }

    private void initialUploadDir() {
        File file = new File(this.uploadPath);
        if (!file.exists()) {
            final boolean createResult = file.mkdirs();
            log.debug("Create upload file directory: {0} result: {1}", file.getAbsolutePath(), createResult);
        }
    }

    @Override
    public String write(InputStream inputStream) {
        String fileName = newFileName();
        String fullPath = uploadPath + fileName;
        try {
            IOUtils.copy(inputStream, new FileOutputStream(fullPath));
            log.debug("Write data to file [" + fullPath + "] finished");
        } catch (IOException e) {
            throw new IllegalStateException("Write file to disk wrong,the file path: " + fullPath, e);
        }
        return fileName;
    }

    protected String newFileName() {
        return UUID.randomUUID().toString();
    }

    @Override
    public String write(byte[] data) {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        return write(bais);
    }

    @Override
    public byte[] read(String path) {
        File file = new File(uploadPath + path);
        try {
            return IOUtils.toByteArray(new FileInputStream(file));
        } catch (IOException e) {
            throw new IllegalStateException("Read file from disk wrong,the file path: " + file.getAbsolutePath(), e);
        }
    }

    @Override
    public void delete(String path) {
        File file = new File(uploadPath + path);
        try {
            FileUtils.forceDelete(file);
        } catch (IOException e) {
            throw new IllegalStateException("Delete file from disk wrong,the file path: " + file.getAbsolutePath(), e);
        }
    }

    @Override
    public String absolutePath(String path) {
        File file = new File(uploadPath + path);
        return file.getAbsolutePath();
    }

    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }


}
